﻿using Ardalis.Specification;
using System.Linq.Expressions;

namespace HuaweiCloud.Dotnet.Samples.Common
{
    public abstract class ApplicationServiceBase<T> : IApplicationService<T> where T : class
    {
        protected readonly IRepository<T> _repository;
        public ApplicationServiceBase(IRepository<T> repository)
        {
            _repository = repository;
        }

        public virtual async Task AddAsync(T t, CancellationToken token = default)
        {
            await _repository.AddAsync(t, token);
        }

        public virtual async Task DeleteAsync<TID>(TID id, CancellationToken token = default) where TID : notnull
        {
            var item = await GetAsync(id, token);
            if(item != null)
                await _repository.DeleteAsync(item, token);
        }

        public virtual async Task<T?> GetAsync<TID>(TID id, CancellationToken token = default) where TID : notnull
        {
            return await _repository.GetByIdAsync(id, token);
        }

        public virtual async Task<IList<T>> ListAsync(ISpecification<T>? specification = null, CancellationToken token = default)
        {
            if (specification != null)
                return await _repository.ListAsync(specification, token);
            else
                return await _repository.ListAsync(token);
        }

        public virtual async Task UpdateAsync(T t, CancellationToken token = default)
        {
            await _repository.UpdateAsync(t, token);
        }
    }
}
